package ServerThreads;

import Client.Client;
import Communication.TaskForModule;
import Const.ClientConst;
import Const.ServerConst;
import LiftEngine.Lift;
import Server.ClientList;
import Server.ServerClientInstance;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;

/**
 *
 * Class description goes here.
 *
 * @author Kamil Gajowy
 */
public class SListener extends MyThreadServer {

    private LinkedList<Thread> clientCommunication;
    private ServerSocket servSock;
    private int nextID = 0;
    private LinkedList<TaskForModule> tList;

    /**
    * Default constructor.
     * @param name
     * @param cListReference
     * @param liftRef
     */
    public SListener(String name, ClientList cListReference, Lift liftRef,
            LinkedList<TaskForModule> taskList){
        super(name,cListReference, liftRef);
        clientCommunication = new LinkedList<Thread>();
        this.tList = taskList;
    }

    @Override
    public void run() {
        init();
        while(serverRunning){
            //accept listeners
            Socket clntSock;
            try {
                clntSock = servSock.accept(); // Get client connection
                //clntSock.setKeepAlive(true);
                String address = clntSock.getInetAddress().getHostAddress();
                int port = clntSock.getPort();
                Client cl = new Client(address,port);

                cl.setCurrentFloor(ClientConst.Undefined);
                cl.setDesiredDirection(ClientConst.Undefined);
                cl.setDesiredFloor(ClientConst.Undefined);
                cl.setState(ClientConst.ClientFree);
                cl.setId(nextID++);
                ServerClientInstance client = new ServerClientInstance(cl,clntSock);
                System.out.println("Incoming client at "
                        + address + " on port " + port);

                Thread fork = new SClientCommunication(
                        "Client"+cl.getId(),
                        this.getClientList(),
                        this.getLiftReference(),
                        client,
                        tList);
                clientCommunication.add(fork);
                fork.start();
                
                //TODO add module to list
                getClientList().getConnectedQueue().addPerson(client);


                System.out.println("\tConnection estabilished.");

            } catch (Exception ex) {
                System.out.println("Client rejected. Reason:"
                        + ex.getMessage());
            }
        }
    }//end run

    private boolean init() {
        System.out.println("\t\t\t opening socket...");
        try {
            servSock = new ServerSocket(ServerConst.Port);
            return true;
        } catch (IOException ex) {
            return false;
        }
    }

    


}//end class
